package com.nickstumpos.android.easyVolume.streams.controller;

import android.content.Context;
import android.media.AudioManager;

import com.nickstumpos.android.easyVolume.streams.types.Stream;
import com.nickstumpos.android.easyVolume.volume.levels.VibrateLevel;
import com.nickstumpos.android.easyVolume.volume.levels.VolumeLevel;
import com.nickstumpos.android.easyVolume.volume.utils.VolumeUtils;

public class StreamController {

	private AudioManager	audioManager;

	public StreamController(Context context) {
		this.audioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
	}

	public VolumeLevel getCurrentVolumeLevel(Stream stream) {
		return VolumeUtils.getCurrentLevel(this.audioManager, stream);
	}

	public boolean isVibeOn(Stream stream) {
		boolean ret = false;
		if (Stream.RINGER.equals(stream)) {
			ret = this.audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER);
		} else if (Stream.NOTIFICATION.equals(stream)) {
			ret = this.audioManager
					.shouldVibrate(AudioManager.VIBRATE_TYPE_NOTIFICATION);
		}
		return ret;
	}

	public void setStreamVolumeLevel(VolumeLevel level, Stream stream) {
		int vol = VolumeUtils.getLevel(this.audioManager.getStreamMaxVolume(stream
				.getAndroidConstant()), level);
		this.audioManager.setStreamVolume(stream.getAndroidConstant(), vol, 0);
		if (Stream.RINGER.equals(stream)) {
			if (VolumeLevel.VIBE_ONLY.equals(level)) {
				this.audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
				this.setVibrate(VibrateLevel.VIBE_ON, stream);
			} else if (VolumeLevel.SILENT.equals(level)) {
				if (Stream.RINGER.equals(stream)) {
					this.audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
				}
				this.setVibrate(VibrateLevel.VIBE_OFF, stream);
			} else {
				this.audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			}
		}
	}

	public void setVibrate(VibrateLevel level, Stream stream) {
		int vibe = level.equals(VibrateLevel.VIBE_ON) ? AudioManager.VIBRATE_SETTING_ON
				: AudioManager.VIBRATE_SETTING_OFF;
		if (Stream.NOTIFICATION.equals(stream)) {
			this.audioManager.setVibrateSetting(
					AudioManager.VIBRATE_TYPE_NOTIFICATION, vibe);
		} else if (Stream.RINGER.equals(stream)) {
			this.audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
					vibe);
		}
	}
}
